<?php

namespace app\controller\api;

use app\common\model\delivery\DeliveryExpressOrder;
use app\common\model\store\order\StoreOrder;
use app\common\model\store\order\StoreOrderExpress;
use app\common\model\store\order\StoreOrderStatus;
use app\common\repositories\delivery\DeliveryExpressOrderRepository;
use app\common\repositories\store\order\StoreOrderStatusRepository;
use app\common\repositories\system\merchant\MerchantRepository;
use crmeb\basic\BaseController;
use Exception;
use think\facade\Cache;
use think\facade\Log;



class Delivery extends BaseController
{


    public function test($field)
    {
        $data99 = $this->request->param();
        try {
            if(isset($data99['callback'])){
                $key = '';
                if(isset($data99['xxx'])){ //快手

                    if(isset($data99['imeiMD5']) && $data99['imeiMD5']!= '' && $data99['imeiMD5'] != '__IMEI2__'){
                        $key = $data99['imeiMD5'];
                    }
                    if(isset($data99['idfa']) && $data99['idfa']!= '' && $data99['idfa'] != '__IDFA2__' && !$key){
                        $key = $data99['idfa'];
                    }
                    if(isset($data99['oaid']) && $data99['oaid']!= '' && $data99['oaid'] != '__OAID__' &&  !$key){
                        $key = $data99['oaid'];
                    }
                    if(isset($data99['androidMD5'])&& $data99['androidMD5']!= '' && $data99['androidMD5'] != '__ANDROIDID2__' && !$key){
                        $key = $data99['androidMD5'];
                    }
                    if(isset($data99['mac']) && $data99['mac']!= '' && $data99['mac'] != '__MAC__' && !$key){
                        $key = $data99['mac'];
                    }
                    $type = 'ks';

                }else{

                    if(isset($data99['oaid'])){
                        $key = $data99['oaid'];
                    }
                    if(isset($data99['androidid']) && !$key){
                        $key = $data99['androidid'];
                    }
                    if(isset($data99['idfa']) && !$key){
                        $key = $data99['idfa'];
                    }
                    $type = 'dy';

                }
                if($key){
                    Cache::set($key, [
                        'os'      => $data99['os'],
                        'type'    =>$type,
                        'callback'=>$data99['callback'],
                        'msg'     =>$data99,
                    ],60*60*3);
                }
                $response = [
                    "code"=> $key ? "0000" : "",
                    "message"=> $key ? "成功" : "失败"
                ];
                return response($response, 200, [], 'json');
            }
        } catch (Exception $e) {
            Log::info('抖音回调:' . var_export([$e->getMessage(), $e->getFile() . ':' . $e->getLine()], true));
        }
    }


    /**
     * @param $field
     * @return \think\Response|void
     * @author: fupeng
     * @day: 2023/12/11
     * 快递回调路由
     * （顺丰）
     */
    public function deliveryExpNotify($field)
    {
        try {
            $param = $this->request->param();
            Log::info('快递回调路由:' . var_export($param, true));
            if(isset($param['Body']['WaybillRoute'])){
                $data = $param['Body']['WaybillRoute'];
                foreach ($data as $v){
                    $expressOrder = (new DeliveryExpressOrder())->where('platform_order_sn',$v['orderid'])->find();
                    if($expressOrder && $expressOrder->returncode != '80'){
                        $expressOrder->returncode = $v['opCode'];
                        $expressOrder->new_delivery_msg = $v['remark'];
                        if($v['opCode'] == '80'){ //快递已签收
                            $expressOrder->status = 4;
                            (new StoreOrderExpress())->where(['express_no' => $v['mailno']])->save(['ischeck'=>1]);
                        }
                        $expressOrder->save();
                    }
                }
                $response = [
                    "return_code"=> "0000",
                    "return_msg"=> "成功"
                ];
                return response($response, 200, [], 'json');
            }
            $response = [
                "return_code"=> "1000",
                "return_msg"=> "系统异常"
            ];
            return response($response, 200, [], 'json');
        } catch (Exception $e) {
            Log::info('快递失败:' . var_export([$e->getMessage(), $e->getFile() . ':' . $e->getLine()], true));
        }
    }

    /**
     * @param $field
     * @return \think\Response|void
     * @author: fupeng
     * @day: 2023/12/11
     * 快递运费推送
     * （顺丰）
     */
    public function deliveryFreightNotify($field)
    {
        try {
            $param = $this->request->param();
            Log::info('快递回调运费:' . var_export($param, true));
            $freight_pay_type = 0;
            sleep(2);
            switch ($field){
                case 'shunfeng' :
                    if(!isset($param['content'])){
                        return response([
                            "code"=> "400",
                            "message"=> "没有content"
                        ], 200, [], 'json');
                    }
                    $content = json_decode($param['content'] ,true);
                    $expressOrder = (new DeliveryExpressOrder())->where('platform_order_sn',$content['orderNo'])->find();
                    if(!$expressOrder){
                        $response =[
                            "code"=> "400",
                            'message'=> '订单信息不存在',
                            // "partnerCode"=>
                        ];
                        return response($response, 200, [], 'json');
                    }
                    if($expressOrder['status'] != 2){
                        $response =[
                            "code"=> "200",
                            'message'=> '快递已推送'
                        ];
                        return response($response, 200, [], 'json');
                    }
                    $fee = 0;
                    $freight_pay_type = 1;
                    foreach ($content['feeList'] as $v){
                        if($v['paymentTypeCode'] == "1" && $v['settlementTypeCode'] == "2"){
                            $fee += $v['feeAmt'];
                            $freight_pay_type = 2;
                        }
                    }
                    $data =[
                        'fee' => $fee,
                        'delivery_product_name'=>$content['productName']??'',
                        'return_msg' => $param['content'],
                        'status' => 3,
                        'freight_pay_type'=>$freight_pay_type
                    ];
                    break;

            }
            $order = (new StoreOrder())->where('order_sn',$expressOrder['order_sn'])->find();
            app()->make(DeliveryExpressOrderRepository::class)->updateDelivery($data,$order);
            $response = [
                "code"=> "200",
                "message"=> ""
            ];
            return response($response, 200, [], 'json');
        } catch (Exception $e) {
            Log::info('快递失败:' . var_export([$e->getMessage(), $e->getFile() . ':' . $e->getLine()], true));
        }
    }

    public function deliveryStatusNotify($field)
    {
        try {
            $param = $this->request->param();
            Log::info('快递状态回调:' . var_export($param, true));
            sleep(1);
            $statusRepository = app()->make(StoreOrderStatusRepository::class);
            $orderStatus =[];
            switch ($field){
                case 'shunfeng' :
                        if(isset($param['orderState']) && count($param['orderState']) > 0){
                        foreach ($param['orderState'] as $v){
                            $expressOrder = (new DeliveryExpressOrder())->where('platform_order_sn',$v['orderNo'])->find();
                            if($expressOrder){
                                $orderStatus[] = [
                                    'order_id' => $expressOrder->order_id,
                                    'order_sn' => $expressOrder->order_sn,
                                    'type' => $statusRepository::TYPE_ORDER,
                                    'change_message' => $v['orderStateDesc'],
                                    'change_type' => 'delivery_0',
                                    'user_type' => 0,
                                    'uid' => 0,
                                    'nickname' => '第三方推送'
                                ];
                            }
                            if(in_array($v['orderStateCode'],['00-40045-1000','04-40002-40014','04-40002-40031','00-40045-40054','00-40045-40046','00-20001','00-2000'])){
                                if($expressOrder->status != '-1'){
                                    app()->make(DeliveryExpressOrderRepository::class)->cancelAfter($expressOrder,0,'');
                                }
                            }else{
                                $expressOrder->new_delivery_msg = $v['orderStateDesc'];
                                $expressOrder->save();
                            }

                        }
                    }
                    break;
            }
            if(count($orderStatus) > 0){
                $statusRepository->batchCreateLog($orderStatus);
            }
            $response = [
                "code"=> "0",
                "success"=> "true",
                "msg"=>""
            ];
            return response($response, 200, [], 'json');
        } catch (Exception $e) {
            Log::info('快递失败:' . var_export([$e->getMessage(), $e->getFile() . ':' . $e->getLine()], true));
        }
    }






}
